/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */
// class Solution {
//     public List<Integer> inorderTraversal(TreeNode root) {
//         List<Integer> list = new ArrayList<>(); 
//         if(root == null) {
//             return list;
//         }
        

//         List<Integer> listLeft = inorderTraversal(root.left);
//         list.addAll(listLeft);

//         list.add(root.val);

//         List<Integer> listRight = inorderTraversal(root.right);
//         list.addAll(listRight);

//         return list;
//     }
// }

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;

        //注意这里的循环条件
        //因为后续cur为空时要弹出栈顶元素，故栈不能为空
        //且一开始时栈为空，故cur不为空就可进入循环
        //当栈空且cur为空，说明前序遍历已完成
        while (cur != null || !stack.isEmpty()) {
            //cur走左子树
            while (cur != null) {
                stack.push(cur);

                cur = cur.left;
            }
            //当cur为空时，弹出栈顶元素（top），添加进顺序表，赋给cur其右子树
            //若cur还是为空（top.right为空），循环过来继续弹出元素，并赋给cur新的top.right
            TreeNode top = stack.pop();
            list.add(top.val);
            cur = top.right;
        }
        return list;
    }
}